package com.centling.smartSealForPhone.utils;

import com.centling.smartSealForPhone.application.SmartSeal;
import com.centling.smartSealForPhone.db.ImageBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 *
 * @author fionera
 * @date 16-4-25
 */
public class OkHttpUtil extends com.wsdk.util.OkHttpUtil {

    public static int count = 0;

    public static void postEnqueueUploadByFile(final List<ImageBean> images, ImageBean image,
                                               String url, String name, String fileName,
                                               String filePath, final NetCallBack responseCallback,
                                               final NetProgressCallback netProgressCallback) {
        if (isNetworkNotConnected(SmartSeal.getInstance())) {
            count++;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onNoNetwork(responseCallback);
                    netProgressCallback.progress(count * 1.0f / images.size());
                }
            });
            return;
        }

        String boundary = "--------------520-13-14";
        File imageFile = new File(filePath);
        if (!imageFile.exists()) {
            count++;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    responseCallback.onSucceed("");
                    netProgressCallback.progress(count * 1.0f / images.size());
                }
            });
            return;
        }
        MultipartBody body = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)
                .addPart(Headers.of("Content-Disposition",
                        "form-data; name=" + name + ";filename=" + fileName),
                        RequestBody.create(MediaType.parse("image/jpeg"), image.getValue()))
                .build();
        Request request = new Request.Builder().url(url).post(body).build();
        final String endUrl = url;
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.d("POST_ERROR - " + endUrl + "\n" + e.getMessage());
                count++;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        responseCallback.onFailed("网络超时");
                        netProgressCallback.progress(count * 1.0f / images.size());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                LogUtil.d("POST_RETURN - " + endUrl + "\n" + result);
                String returnCode = "404";
                String returnMsg = "网络超时";
                try {
                    returnCode = new JSONObject(result).getString("returnCode");
                    returnMsg = new JSONObject(result).getString("returnMsg");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final String finalMsg = returnMsg;
                if ("200".equals(returnCode)) {
                    count++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String finalResult = new JSONObject(result).getJSONObject(
                                        "returnData").toString();
                                responseCallback.onSucceed(finalResult);
                                netProgressCallback.progress(count * 1.0f / images.size());
                            } catch (JSONException ignore) {
                            }
                        }
                    });
                } else {
                    count++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            responseCallback.onFailed(finalMsg);
                            netProgressCallback.progress(count * 1.0f / images.size());
                        }
                    });
                }
            }
        });
    }

    public interface NetProgressCallback extends com.wsdk.util.OkHttpUtil.NetProgressCallback {

    }

    public interface NetCallBack extends com.wsdk.util.OkHttpUtil.NetCallBack {

    }

    public interface NoNetCallBack
            extends com.wsdk.util.OkHttpUtil.NoNetCallBack {
    }
}
